package com.xy.xymall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xy.common.exception.BizCodeEnum;
import com.xy.common.utils.HttpUtils;
import com.xy.xymall.member.dao.MemberLevelDao;
import com.xy.xymall.member.entity.MemberLevelEntity;
import com.xy.xymall.member.error.MemberExceptionCodeEnum;
import com.xy.xymall.member.exception.MemberException;
import com.xy.xymall.member.service.MemberLevelService;
import com.xy.xymall.member.vo.MemberLoginVo;
import com.xy.xymall.member.vo.MemberRegistVo;
import com.xy.xymall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.common.utils.PageUtils;
import com.xy.common.utils.Query;

import com.xy.xymall.member.dao.MemberDao;
import com.xy.xymall.member.entity.MemberEntity;
import com.xy.xymall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @param registVo
     * @author XY
     * @date 2020/10/20 15:20
     * @return void
     * 用户注册功能
     */
    @Override
    public void regist(MemberRegistVo registVo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity=memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名和手机号是否唯一
        checkPhoneUnique(registVo.getPhone());
        checkUserNameUnique(registVo.getUserName());
        memberEntity.setUsername(registVo.getUserName());
        memberEntity.setMobile(registVo.getPhone());
        memberEntity.setNickname(registVo.getUserName());
        //密码加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(registVo.getPassword());
        memberEntity.setPassword(password);
        //其他。。。
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkEmailUnique(String email) {
    }

    @Override
    public void checkUserNameUnique(String userName) throws MemberException{
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(count>0){
            throw new MemberException(BizCodeEnum.USERNAME_EXISTED.getMessage());
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws MemberException{
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count>0){
            throw new MemberException(BizCodeEnum.PHONE_EXISTED.getMessage());
        }
    }

    /**
     * @param loginVo
     * @author XY
     * @date 2020/10/20 15:20
     * @return com.xy.xymall.member.entity.MemberEntity
     * 用户登录功能
     */
    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", username)
                .or().eq("mobile", username));
        if(memberEntity == null){
            //登录失败
            return null;
        }else{
            //数据库的password
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            //页面输入的密码跟数据库加密的密码进行匹配
            boolean flag = bCryptPasswordEncoder.matches(password, passwordDb);
            if(flag){
                return memberEntity;
            }else{
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //社交登录和注册合并逻辑
        String uid = socialUser.getUid();
        //判断当前社交用户是否已经注册过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity!=null){
            //这个用户已经注册过
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            //更新用户从社交平台获取的token和过期时间
            this.baseMapper.updateById(memberEntity);
            return memberEntity;
        }else{
            //没有查到则注册一个
            MemberEntity regist = new MemberEntity();
            try{
                //查询当前社交账户的社交账号信息
                Map<String, String> map=new HashMap<>();
                map.put("access_token",socialUser.getAccess_token());
                map.put("uid",socialUser.getUid());
                //从社交平台获取到用户信息
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);
                if(response.getStatusLine().getStatusCode()==200) {
                    String string = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(string);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            }catch (Exception e){

            }
            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.insert(regist);
            return regist;
        }
    }
}